package com.ooqiu.gaming.components.retrofit.convert;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.ooqiu.gaming.api.base.BaseRequest;
import com.ooqiu.gaming.components.storage.UserStorage;
import com.ooqiu.gaming.ui.login.LoginActivity;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Converter;

/**
 * @author baronzhang (baron[dot]zhanglei[at]gmail[dot]com)
 *         16/2/25
 */
final class FastJsonRequestBodyConverter<T> implements Converter<T, RequestBody> {

    private static final MediaType MEDIA_TYPE = MediaType.parse("application/x-www-form-urlencoded");

    private SerializeConfig serializeConfig;
    private UserStorage mUserStorage;

    public FastJsonRequestBodyConverter(SerializeConfig serializeConfig, UserStorage userStorage) {
        this.mUserStorage = userStorage;
        this.serializeConfig = serializeConfig;
    }

    @Override
    public RequestBody convert(T value) throws IOException {
        BaseRequest request = JSON.parseObject(JSON.toJSONString(value), BaseRequest.class);
//        LogUtil.json(request);
        if (request.isNeedLogin()) {
            if (request.isForceLogin() ) {
                if (mUserStorage.isLogin()) {
                    request.setToken(mUserStorage.getToken());
                    return RequestBody.create(MEDIA_TYPE, request.getBodyStr());
                } else {
                    ARouter.getInstance().build(LoginActivity.PATH).greenChannel().navigation();
                    throw new IllegalStateException("请先登录");
//                    throw new IllegalStateException("the user is null,need to login");
                }

            } else {
                request.setToken(mUserStorage.getToken());
                return RequestBody.create(MEDIA_TYPE, request.getBodyStr());
            }
        } else {

            return RequestBody.create(MEDIA_TYPE, request.getBodyStr());
        }

    }
}
